package com.mr.security.web.commons.handler;

import com.mr.security.web.commons.config.SecurityPropertiesConfig;
import com.mr.security.web.commons.utils.ConstantEnum;
import com.mr.security.web.commons.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Class: CustomAuthenticationSuccessHandle
 * User (作者):MRui
 * TODO (描述)：身份验证成功处理
 * Date 2019-01-20 14:47
 */
@Slf4j
@Component
public class CustomAuthenticationSuccessHandle extends SimpleUrlAuthenticationSuccessHandler {

    /** 属性配置类 */
    @Autowired
    private SecurityPropertiesConfig securityProperties;


    /**
    * User (作者): MRui
    * TODO (描述)：重写登陆身份验证成功后的方法
    * Data：2019-01-20 14:48
    */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        String  username = authentication.getName();
        //如果方式是返回json的方式（前后端分离）
        if (ConstantEnum.AUTHENTICATION_JSON.getMessage().equals(securityProperties.getLoginType())){
            log.info("用户:{},身份验证成功！准许登陆",username);
            //将authentication转换json后返回给前台
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JsonUtil.toJson(authentication));
        }else {
            //调用父类方法（跳转）
            log.info("用户:{},身份验证成功！准许登陆",username);
            //super.setAlwaysUseDefaultTargetUrl(false);
            //修改默认跳转地址（登陆后跳转的地址）
            super.setDefaultTargetUrl("/toIndex.do");
            super.onAuthenticationSuccess(request,response,authentication);
        }
    }
}
